package com.ewei.web.authority.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ewei.web.common.utils.Encrypter;

@Component
public class TokenUtilsImpl implements TokenUtils {
	@Resource
	private Encrypter encrypter = new Encrypter();
	@Value("${session.encrpter.key}")
	private String appKey = "chenhua";//登陆的密钥
	@Override
	public boolean validate(String token,String auth) {
		String authDecode = null;
		try {
			authDecode =  encrypter.base64Decoder(auth);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(null == authDecode){
			return false;
		}
		String timeStamp = getTimeFromAuth(authDecode);
		String userName = getUserNameFromAuth(authDecode);
		String tokenValidate = new SimpleHash("md5", appKey+timeStamp+userName,timeStamp, 2).toHex();//运用shiro自带的加密方式,用时间参数作盐
		if(token.equals(tokenValidate)){
			return true;
		}
		return false;
	}

	@Override
	public String getUserNameFromAuth(String authDecode) {
		return authDecode.substring(0,authDecode.length()- 14);
	}

	@Override
	public String getTimeFromAuth(String authDecode) {
		return authDecode.substring(authDecode.length() - 14);
	}

	@Override
	public String generateToken(String userName) {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String timeStamp = format.format(new Date());
		String token = new SimpleHash("md5", appKey+timeStamp+userName,timeStamp, 2).toHex();//运用shiro自带的加密方式
		return token;
	}

	@Override
	public String generateAuth(String username) {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String timeStamp = format.format(new Date());
		String auth = null;
		try {
			 auth  = encrypter.base64Encoder(username+timeStamp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return auth;
	}

}
